package org.jianfa.learn.controller;

import org.jianfa.learn.entity.Article;
import org.jianfa.learn.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;

@Controller
@RequestMapping("/")
public class ArticleController {

    @Autowired
    private ArticleRepository articleRepository;

    @GetMapping("index")
    public String index(Model model,
                        @RequestParam(name = "page", required = false) Integer page) {
        if (page == null) {
            page = 0;
        } else {
            page = page - 1;
        }

        PageRequest pageRequest = PageRequest.of( page, 3);
        Page<Article> articlesPage = articleRepository.findAll(pageRequest);
        model.addAttribute("articlesPage", articlesPage);
        model.addAttribute("pages", Arrays.asList(1, 2));
        return "client/index";
    }

    @GetMapping("page")
    public String page(Model model, @RequestParam(name = "action") String action,
                       @RequestParam(name = "curPage", required = false) Integer curPage,
                       @RequestParam(name = "totalPage", required = false) Integer totalPage) {

        //首页
        if ("first".equals(action)) {
            curPage = 0;
        }

        //上一页
        if ("previous".equals(action)) {
            curPage = curPage - 1;
            if (curPage < 0) {
                curPage = 0;
            }
        }

        //下一页
        if("next".equals(action)) {
            curPage = curPage + 1;
            if (curPage > (totalPage - 1)) {
                curPage = (totalPage - 1);
            }
        }

        //尾页
        if("last".equals(action)) {
            curPage = (totalPage - 1);
        }

        //
        PageRequest pageRequest = PageRequest.of( curPage, 3);
        Page<Article> articlesPage = articleRepository.findAll(pageRequest);
        model.addAttribute("articlesPage", articlesPage);
        model.addAttribute("pages", Arrays.asList(1, 2));
        return "client/index";
    }

}
